const db = require('../config/db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { jwtSecretKey } = require('../config/jwtSecretKey');
/**
 * 注册接口逻辑
 */
exports.registerController = (req, res) => {
  // 用户名或者密码判空的校验
  let { userName, password } = req.body;
  if (!userName || !password) {
    return res.send({ code: 1, message: '用户名或者密码不能为空！' });
  }
  // 用户名查重的逻辑
  const userSelectSql = 'select * from user where name=?';
  db.query(userSelectSql, userName, (err, results) => {
    if (err) {
      return res.send({ code: 1, message: err.message });
    }

    //判断用户是否在数据库中存在
    if (results.length > 0) {
      return res.send({ code: 1, message: '该用户名已经存在' });
    }

    //用户密码加密
    const bcrypt = require('bcryptjs');
    const passwordB = bcrypt.hashSync(password, 10);

    //随机生成用户的头像
    const imgList = [
      '不吃奶拖01.jpg',
      '五条悟.jpg',
      '佘姐.jpg',
      '佘姐02.jpg',
      '宁智波鼬.jpg',
      '教父.jpg',
      '索隆01.png',
      '路飞.jpg',
      '鸣人.jpg',
    ];
    // Math.random(); 结果为0-1间的一个随机数(包括0,不包括1) Math.ceil(Math.random()*10);
    // const num = Math.floor(Math.random() * 10);

    //生成随机整数[min,max]
    const getRandomIntegers = (min, max) => {
      return Math.round(Math.random() * (max - min)) + min;
    };
    
    const num = getRandomIntegers(0, imgList.length - 1);



    //用户信息插入数据库
    const userInsertSql = 'insert into user (name,pwd,head_img) value (?,?,?)';
    db.query(
      userInsertSql,
      [userName, passwordB, imgList[num]],
      (err, results) => {
        if (err) {
          return res.send({ code: 1, message: err.message });
        }
        res.send({
          code: 0,
          message: '注册成功',
        });
      }
    );
  });
};

/**
 * 登录接口逻辑
 */
exports.loginController = (req, res) => {
  let { userName, password } = req.body;

  const userSelectSql = 'select * from user where name=?';
  db.query(userSelectSql, userName, (err, results) => {
    //错误日志返回
    if (err) {
      return res.send({ code: 1, message: err.message });
    }

    //账号存在与否判断
    if (results.length === 0) {
      return res.send({ code: 1, message: '账号不存在，请先注册！' });
    }

    //判断密码是否正确
    const compareState = bcrypt.compareSync(password, results[0].pwd);
    if (!compareState) {
      return res.send({ code: 1, message: '密码错误！' });
    }

    //声明需要拼接token的用户信息
    const user = { ...results[0], pwd: '' };

    //生成token
    const token = jwt.sign(user, jwtSecretKey, { expiresIn: '24h' });

    //响应数据
    res.send({
      code: 0,
      data: {
        token: 'Bearer ' + token,
      },
      message: '登录成功',
    });
  });
};

/**
 * 用户信息查询逻辑
 */
exports.userInfoController = (req, res) => {
  //获取token
  const token = req.headers.authorization;
  //解析token获取用户数据
  const userInfo = jwt.verify(token.split('Bearer ')[1], jwtSecretKey);

  res.send({
    code: 0,
    data: { name: userInfo.name, headImg: userInfo.head_img },
  });
};

/**
 * 用户列表查询接口
 */

exports.userFindeController = (req, res) => {
  let { page, size } = req.query;
  currPgDataIndex = (page - 1) * size;
  // 查询用户列表的sql
  const userListSql = 'select * from user order by id limit ?,?';
  // 查询用户总数的sql
  const userTotalSql = 'select count(*) as total from user';

  db.query(
    userListSql,
    [Number(currPgDataIndex), Number(size)],
    (err, userList) => {
      //处理一下userlist使其隐藏掉密码
      userList.map((item) => {
        item.pwd = '';
      });

      if (err) {
        return res.send({ code: 1, message: err.message });
      } else {
        db.query(userTotalSql, (err, userTotal) => {
          if (err) {
            return res.send({ code: 1, message: err.message });
          }
          res.send({
            code: 0,
            data: {
              list: userList,
              total: userTotal,
            },
          });
        });
      }
    }
  );
};
